<?php

namespace app\common\service\tencent;

require_once root_path() . 'extend/tencent/vendor/autoload.php';

use app\admin\service\work_area\BusinessService;
use app\common\model\haikang\HkEventType;
use app\common\model\work_area\HkDeviceSerial;
use app\common\model\work_area\WorkAreaStand;
use app\common\model\work_area\WorkAreaStandVoice;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Tts\V20190823\TtsClient;
use TencentCloud\Tts\V20190823\Models\TextToVoiceRequest;
use think\facade\Env;


/**
 * 腾讯语音服务
 */
class VoiceService
{

    /**
     * 接口获取音频
     * @param $params
     * @return string
     */
    public static function saveVoice($params)
    {
        // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
        // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
        // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
        $cred = new Credential(Env::get('TencentCloud.SecretId'), Env::get('TencentCloud.SecretKey'));
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("tts.tencentcloudapi.com");

        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        $client = new TtsClient($cred, "ap-chengdu", $clientProfile);

        // 实例化一个请求对象,每个接口都会对应一个request对象
        $req = new TextToVoiceRequest();
        $req->fromJsonString(json_encode($params));
        // 返回的resp是一个TextToVoiceResponse的实例，与请求对象对应
        $resp = $client->TextToVoice($req);
        // 输出json格式的字符串回包
        $resp = json_decode($resp->toJsonString(), true);
        // 解码 Base64 字符串为二进制数据
        $audioData = base64_decode($resp['Audio']);

        $directory = 'voice/' . date('Ymd');
        if (!file_exists($directory)) mkdir($directory, 0775, true);

        // 创建一个新的文件来保存音频数据
        $filename = $directory . '/' . random_string(8) . 'audio.wav'; // 文件名可以自定义，根据需要修改后缀名
        // 写入音频数据到文件
        file_put_contents($filename, $audioData);

        return $filename;
    }

    /**
     * 获取指定站点所有的事件语音
     * @param $work_area_stand_id
     * @return void
     */
    public static function workAreaStand($hk_device_serial)
    {
        $work_area_stand = HkDeviceSerial::where(['id' => $hk_device_serial])->field(['id', 'name', 'comply_with', 'remarks'])->find()->toArray();
        //只获取下面数组事件
        
        $event_arr_id = HkEventType::$event_arr_id;
        $hk_event_type = HkEventType::where(['id' => $event_arr_id])->column('voice', 'remarks');
        
        foreach ($hk_event_type as $key => $val) {
            $Text = "{$work_area_stand['remarks']},{$val},{$work_area_stand['comply_with']}";
            $info = WorkAreaStandVoice::where([
                'hk_device_serial_id' => $hk_device_serial,
                'event_type' => $key,
                'text' => $Text
            ])->find();
            
            if (empty($info)) {
                $params = [
                    "Text" => $Text,
                    "SessionId" => "work_area_stand{$hk_device_serial}",
                    "Volume" => 10,
                    "Speed" => 0
                ];
                $res = self::saveVoice($params);
                $info = WorkAreaStandVoice::where([
                    'hk_device_serial_id' => $hk_device_serial,
                    'event_type' => $key,
                ])->find();
                if (empty($info)) {
                    WorkAreaStandVoice::create([
                        'hk_device_serial_id' => $hk_device_serial,
                        'event_type' => $key,
                        'file' => $res,
                        'text' => $Text
                    ]);
                } else {
                    $info->file = $res;
                    $info->text = $Text;
                    $info->save();
                }
            }
        }
    }

}